import requests
from lxml import etree
# 封装类，进行学习猿地的登陆的订单的获取

class MonKey():
    # 登陆请求网址：
    url = 'https://www.lmonkey.com/login'
    ordurl = 'https://www.lmonkey.com/my/order'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'
    }
    # 请求对象
    req = None
    #token 口令
    token = ''
    # 订单号：
    code = 0
    # 初始话对象
    def __init__(self):
        self.req = requests.session()
        if self.getlogin():
            if self.postcode():
                self.getorder()

    # get 登陆页面 获取_token

    def getlogin(self):
        res = self.req.get(url=self.url,headers=self.headers)
        if res.status_code == 200:
            print("get 登陆页面成功")
            html = etree.HTML(res.text)
            self.token = html.xpath('//meta[@name="csrf-token"]/@content')[0]
            print(self.token)
            print('请求成功')
            return True
        else:
            print('请求失败')

    # post请求
    def postcode(self):
        username = input('手机号')
        password = input('密码')
        data = {
            'username':username,
            'password':password,
            '_token':self.token
        }
        # 发起请求
        res = self.req.post(url=self.url,headers=self.headers,data=data)
        if res.status_code == 200 or res.status_code == 302:
            print('post登陆成功')
            return True

    # get 请求账户中心
    def  getorder(self):
        res = self.req.get(url=self.ordurl,headers=self.headers)
        if res.status_code == 200:
            with open('./7.0 text.html', 'w', encoding='utf-8') as book:
                book.write('%s' % res.content.decode('utf-8'))
            print('账户请求成功，正在解析数据---')
            html = etree.HTML(res.text)
            self.code = html.xpath('//div [@class="avatar-content"]//small/text()')
            print(self.code[0])
            return True


l = MonKey()



'''
1.get请求 login页面，设置cookie ,获取 token
2.post 请求 提交登陆数据，进行登陆，并且设置cookie
3.get请求账户中心 获取默认的订单号

'''